/*
 * @Date: 2023-12-21 10:39:12
 * @LastEditors: lyx
 * @LastEditTime: 2023-12-29 09:10:16
 * @FilePath: \taro-template3\src\components\IntlElement\index.tsx
 * @Description:
 */
import { useGlobalData } from "@/store/app";
import { useLaunch } from "@tarojs/taro";
import { useState } from "react";
import { IntlProvider } from "react-intl";
import enUS from "../../locales/en-US.json";
import zhCN from "../../locales/zh-CN.json";
import "intl";
import "intl/locale-data/jsonp/en.js";
import "intl/locale-data/jsonp/zh.js";

const messages = {
  en: enUS,
  zh: zhCN,
};

const IntlElement = ({ children }) => {
  const { env, systemInfo } = useGlobalData();
  const [locale, setLocale] = useState("zh");

  useLaunch((options) => {
    if (["WEAPP", "QYWX"].includes(env)) {
      setLocale(systemInfo?.language?.split(/[-_]/)[0] || "zh");
    }
    if (["H5"].includes(env)) {
      setLocale(navigator?.language?.split(/[-_]/)[0] || "zh");
    }
  });

  return (
    <IntlProvider locale={locale} messages={messages[locale]}>
      {children}
    </IntlProvider>
  );
};

export default IntlElement;
